<template>
  <div class="table-container">
    <!-- 搜索区域 -->
    <div v-if="showSearch" class="table-search">
      <el-form
        ref="searchFormRef"
        :model="searchForm"
        :inline="true"
        @keyup.enter="handleSearch"
      >
        <slot name="search">
          <el-form-item
            v-for="item in searchItems"
            :key="item.prop"
            :label="item.label"
            :prop="item.prop"
          >
            <el-input
              v-if="item.type === 'input'"
              v-model="searchForm[item.prop]"
              :placeholder="item.placeholder"
              clearable
              @clear="handleSearch"
            />
            
            <el-select
              v-else-if="item.type === 'select'"
              v-model="searchForm[item.prop]"
              :placeholder="item.placeholder"
              clearable
              @clear="handleSearch"
            >
              <el-option
                v-for="option in item.options"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
            
            <el-date-picker
              v-else-if="item.type === 'date'"
              v-model="searchForm[item.prop]"
              :type="item.dateType || 'date'"
              :placeholder="item.placeholder"
              clearable
              @clear="handleSearch"
            />
            
            <el-date-picker
              v-else-if="item.type === 'daterange'"
              v-model="searchForm[item.prop]"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              clearable
              @clear="handleSearch"
            />
          </el-form-item>
        </slot>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 工具栏 -->
    <div v-if="showToolbar" class="table-toolbar">
      <div class="left">
        <slot name="toolbar-left">
          <el-button
            v-if="showAdd"
            type="primary"
            @click="handleAdd"
          >
            <el-icon><Plus /></el-icon>
            新增
          </el-button>
          <el-button
            v-if="showDelete"
            type="danger"
            :disabled="!selectedRows.length"
            @click="handleDelete"
          >
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </slot>
      </div>
      
      <div class="right">
        <slot name="toolbar-right">
          <el-button
            v-if="showRefresh"
            @click="handleRefresh"
          >
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
          <el-button
            v-if="showColumnSetting"
            @click="showColumnSettingDialog = true"
          >
            <el-icon><Setting /></el-icon>
            列设置
          </el-button>
        </slot>
      </div>
    </div>
    
    <!-- 表格 -->
    <el-table
      ref="tableRef"
      v-bind="$attrs"
      v-loading="loading"
      :data="tableData"
      :border="border"
      :stripe="stripe"
      :row-key="rowKey"
      :selection="selection"
      @selection-change="handleSelectionChange"
    >
      <!-- 选择列 -->
      <el-table-column
        v-if="selection"
        type="selection"
        width="55"
        align="center"
        fixed="left"
      />
      
      <!-- 序号列 -->
      <el-table-column
        v-if="showIndex"
        type="index"
        label="序号"
        width="60"
        align="center"
        fixed="left"
      />
      
      <!-- 数据列 -->
      <template v-for="column in visibleColumns" :key="column.prop">
        <el-table-column
          v-bind="column"
          :align="column.align || 'center'"
        >
          <template #default="scope" v-if="column.slot">
            <slot :name="column.slot" :row="scope.row" :index="scope.$index" />
          </template>
        </el-table-column>
      </template>
      
      <!-- 操作列 -->
      <el-table-column
        v-if="showOperation"
        label="操作"
        :width="operationWidth"
        align="center"
        fixed="right"
      >
        <template #default="scope">
          <slot name="operation" :row="scope.row" :index="scope.$index">
            <el-button
              v-if="showEdit"
              type="primary"
              link
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="showDelete"
              type="danger"
              link
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </slot>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div v-if="showPagination" class="table-pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="pageSizes"
        :layout="paginationLayout"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 列设置对话框 -->
    <el-dialog
      v-model="showColumnSettingDialog"
      title="列设置"
      width="500px"
      append-to-body
    >
      <el-checkbox-group v-model="visibleColumnProps">
        <el-checkbox
          v-for="column in columns"
          :key="column.prop"
          :label="column.prop"
          :disabled="column.fixed"
        >
          {{ column.label }}
        </el-checkbox>
      </el-checkbox-group>
      
      <template #footer>
        <el-button @click="showColumnSettingDialog = false">取消</el-button>
        <el-button type="primary" @click="handleColumnSettingConfirm">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Plus,
  Delete,
  Setting
} from '@element-plus/icons-vue'

const props = defineProps({
  // 表格数据
  data: {
    type: Array,
    default: () => []
  },
  // 表格列配置
  columns: {
    type: Array,
    default: () => []
  },
  // 是否显示边框
  border: {
    type: Boolean,
    default: true
  },
  // 是否显示斑马纹
  stripe: {
    type: Boolean,
    default: true
  },
  // 行数据的 Key
  rowKey: {
    type: String,
    default: 'id'
  },
  // 是否显示多选
  selection: {
    type: Boolean,
    default: false
  },
  // 是否显示序号
  showIndex: {
    type: Boolean,
    default: true
  },
  // 是否显示操作列
  showOperation: {
    type: Boolean,
    default: true
  },
  // 操作列宽度
  operationWidth: {
    type: [String, Number],
    default: 150
  },
  // 是否显示编辑按钮
  showEdit: {
    type: Boolean,
    default: true
  },
  // 是否显示删除按钮
  showDelete: {
    type: Boolean,
    default: true
  },
  // 是否显示搜索区域
  showSearch: {
    type: Boolean,
    default: true
  },
  // 搜索项配置
  searchItems: {
    type: Array,
    default: () => []
  },
  // 是否显示工具栏
  showToolbar: {
    type: Boolean,
    default: true
  },
  // 是否显示新增按钮
  showAdd: {
    type: Boolean,
    default: true
  },
  // 是否显示刷新按钮
  showRefresh: {
    type: Boolean,
    default: true
  },
  // 是否显示列设置按钮
  showColumnSetting: {
    type: Boolean,
    default: true
  },
  // 是否显示分页
  showPagination: {
    type: Boolean,
    default: true
  },
  // 分页布局
  paginationLayout: {
    type: String,
    default: 'total, sizes, prev, pager, next, jumper'
  },
  // 每页条数选项
  pageSizes: {
    type: Array,
    default: () => [10, 20, 50, 100]
  },
  // 加载状态
  loading: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits([
  'update:data',
  'search',
  'reset',
  'add',
  'edit',
  'delete',
  'refresh',
  'selection-change',
  'page-change',
  'size-change'
])

// 表格引用
const tableRef = ref(null)
const searchFormRef = ref(null)

// 搜索表单
const searchForm = ref({})

// 表格数据
const tableData = computed({
  get: () => props.data,
  set: (val) => emit('update:data', val)
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(props.pageSizes[0])
const total = ref(0)

// 列设置相关
const showColumnSettingDialog = ref(false)
const visibleColumnProps = ref(props.columns.map(col => col.prop))
const visibleColumns = computed(() => 
  props.columns.filter(col => visibleColumnProps.value.includes(col.prop))
)

// 选中的行
const selectedRows = ref([])

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  emit('search', searchForm.value)
}

// 处理重置
const handleReset = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
  emit('reset')
}

// 处理新增
const handleAdd = () => {
  emit('add')
}

// 处理编辑
const handleEdit = (row) => {
  emit('edit', row)
}

// 处理删除
const handleDelete = (row) => {
  const rows = row ? [row] : selectedRows.value
  
  ElMessageBox.confirm(
    `确认删除选中的 ${rows.length} 条数据吗？`,
    '提示',
    {
      type: 'warning'
    }
  ).then(() => {
    emit('delete', rows)
  })
}

// 处理刷新
const handleRefresh = () => {
  handleSearch()
  emit('refresh')
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
  emit('selection-change', selection)
}

// 处理列设置确认
const handleColumnSettingConfirm = () => {
  showColumnSettingDialog.value = false
}

// 处理页码变化
const handleCurrentChange = (page) => {
  emit('page-change', page)
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  emit('size-change', size)
}

// 监听搜索项变化
watch(() => props.searchItems, (items) => {
  const form = {}
  items.forEach(item => {
    form[item.prop] = undefined
  })
  searchForm.value = form
}, { immediate: true })

// 暴露方法
defineExpose({
  // 获取表格实例
  getTable: () => tableRef.value,
  // 获取搜索表单实例
  getSearchForm: () => searchFormRef.value,
  // 获取选中的行
  getSelectedRows: () => selectedRows.value,
  // 清空选择
  clearSelection: () => tableRef.value?.clearSelection(),
  // 刷新表格
  refresh: handleRefresh,
  // 重置搜索
  reset: handleReset
})
</script>

<style lang="scss" scoped>
.table-container {
  .table-search {
    margin-bottom: 16px;
    padding: 16px;
    background-color: #fff;
    border-radius: 4px;
  }
  
  .table-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    
    .left {
      display: flex;
      gap: 8px;
    }
    
    .right {
      display: flex;
      gap: 8px;
    }
  }
  
  .table-pagination {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 